package com.tech.platform.cms.authz.sso.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tech.platform.cms.authz.common.model.LoginUserModel;
import com.tech.platform.cms.authz.sso.dao.bean.SubSystem;
import com.tech.platform.cms.authz.sso.dao.bean.TenantUser;
import com.tech.platform.cms.authz.sso.dao.mapper.SubSystemMapper;
import com.tech.platform.cms.authz.sso.dao.mapper.TenantUserMapper;
import com.tech.platform.cms.authz.sso.exception.LoginException;
import com.tech.platform.cms.authz.sso.exception.NoSuchClientException;
import com.tech.platform.cms.authz.sso.exception.NoSuchHgcTokenException;
import com.tech.platform.cms.authz.sso.exception.NoSuchHgtTokenException;
import com.tech.platform.cms.authz.sso.utils.JwtRedisUtils;
import com.tech.platform.cms.common.constant.Constant;
import com.tech.platform.cms.common.model.CommonResult;
import com.tech.platform.cms.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Service
@Slf4j
public class SsoAuthzService {

    @Autowired
    private JwtTokenService jwtTokenService;

    @Autowired
    private JwtRedisUtils jwtRedisUtils;

    @Autowired
    private SubSystemMapper subSystemMapper;

    @Autowired
    private TenantUserMapper tenantUserMapper;

    public CommonResult<String> checkHgtToken(HttpServletRequest request) throws NoSuchHgtTokenException {
        String clientId = request.getHeader("clientId");
        String token = request.getHeader("Authorization");
        LoginUserModel loginUserModel = jwtTokenService.getLoginUserModel(clientId,token);
        String redisToken = jwtRedisUtils.getHgtToken(clientId,loginUserModel.getUserId());
        if(token.equals(redisToken)){
            return new CommonResult<>(Constant.SUCCESS,"check success",token);
        }

        throw new NoSuchHgtTokenException(new Exception("hgt token 错误"));
    }

    public CommonResult<String> exchangeHgtToken(HttpServletRequest httpServletRequest){
        String token = httpServletRequest.getHeader("hgcToken");
        String clientId = httpServletRequest.getHeader("clientId");
        LoginUserModel loginUserModel = jwtTokenService.getLoginUserModel(token);
        String redisToken = jwtRedisUtils.getHgcToken(loginUserModel.getUserId());
        if(!token.equals(redisToken)){
            throw new NoSuchHgcTokenException(new Exception("找不到用户的hgc token"));
        }

        //TODO 查询需要兑换token的用户子系统权限角色信息
        String hgtToken = jwtTokenService.generatorHgtToken(clientId,loginUserModel);
        return new CommonResult<>(Constant.SUCCESS,"success",hgtToken);
    }

   public String makeCookieAndGetRedirectUrl(LoginUserModel userModel,HttpServletRequest request,HttpServletResponse response) throws NoSuchClientException {
       String referer = request.getHeader("Referer");
       String redirectUrl = "";
       String clientId="";
       if(referer.indexOf("?")>0){
           String queryStr = referer.substring(referer.indexOf("?")+1);
           Map<String,String> queryMap = StringUtils.queryStrToMap(queryStr);
           redirectUrl = queryMap.get("redirectUrl");
           clientId = queryMap.get("clientId");
       }

       if(StrUtil.isBlank(clientId)){
           clientId = request.getParameter("clientId");
       }

       if(StrUtil.isBlank(redirectUrl)){
           QueryWrapper<SubSystem> wrapper = new QueryWrapper<>();
           wrapper.eq("system_id",clientId);
           SubSystem subSystem = subSystemMapper.selectOne(wrapper);
           if(ObjectUtil.isNull(subSystem)){
               throw new NoSuchClientException();
           }

           redirectUrl = subSystem.getRedirectUrl();
       }

       String hgcToken = jwtTokenService.generatorHgcToken(userModel);
       Cookie hgcTokenCookie = new Cookie("hgcToken",hgcToken);
       hgcTokenCookie.setDomain("dyadmin.com");
       hgcTokenCookie.setPath("/");
       hgcTokenCookie.setHttpOnly(true);
       response.addCookie(hgcTokenCookie);
       return redirectUrl;
   }

   public LoginUserModel login(String userName,String password,String tenantId){
       QueryWrapper<TenantUser> queryWrapper = new QueryWrapper<>();
       queryWrapper.eq("username",userName);
       queryWrapper.eq("tenant_id",tenantId);
       TenantUser tenantUser = tenantUserMapper.selectOne(queryWrapper);
       if(ObjectUtil.isNull(tenantUser)){
           throw new LoginException(501,"用户名不存在或者企业标识");
       }

       String pwd = MD5.create().digestHex(password+tenantUser.getSalt());
       if(!pwd.equals(tenantUser.getPassword())){
           throw new LoginException(501,"密码错误");
       }

       LoginUserModel loginUserModel = new LoginUserModel();
       loginUserModel.setUserId(tenantUser.getId())
               .setUserName(tenantUser.getUsername())
               .setTenant(tenantId);
       return loginUserModel;
   }
}
